package com.drdg.netty.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.drdg.netty.agreement.MsgAgreement;
import com.drdg.netty.bean.InformationPacket;
import com.drdg.netty.bean.InformationPacket.Group;
import com.drdg.netty.service.MessageHanlderFactory;
import com.drdg.netty.service.MsgHandleService;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class TimeServerHandler extends ChannelHandlerAdapter {

	MsgAgreement msgAgree = new MsgAgreement(true);
	MessageHanlderFactory msgFactory=new MessageHanlderFactory();
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		
		MsgHandleService.channelGroup.add(ctx.channel());
		MsgHandleService.userMap.put(ctx.channel().id().toString(), ctx);
		
		System.out.println("登录"+MsgHandleService.channelGroup.size());
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		MsgHandleService.channelGroup.remove(ctx.channel());
		MsgHandleService.userMap.remove(ctx.channel().id().toString());
		MsgHandleService.userList.remove(ctx.channel().id().toString());
		System.out.println("退出");
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		
		InformationPacket.Group group = (Group) msg;
		//这个地方可能会阻塞，需要异步的线程处理
		msgFactory.doWork(msgAgree, ctx, group);
		
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		ctx.close();
	}
	
}
